<template>
    <div class="login">
        <div class="login-box">
            <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm">
                <el-form-item prop="username">
                    <el-input size="large" v-model="ruleForm.username" type="text" placeholder="请输入用户名">
                        <template #prefix>
                            <el-icon class="el-input__icon">
                                <UserFilled />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input size="large" v-model="ruleForm.password" type="password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { LoginApi } from '@/api'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter();

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
    username: '',
    password: '',
})

const rules = reactive<FormRules>({
    username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
    password: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: boolean) => {
        if (valid) {
            // 校验通过 ， 向服务器发请求
            LoginApi(ruleForm).then(res => {
                if (res.code === 200) {
                    // 登录成功
                    // 提示
                    ElMessage({
                        message: '登录成功',
                        type: 'success',
                    })
                    // token
                    localStorage.setItem('token', res.data.tokenHead + res.data.token)
                    // 跳转
                    router.push('/home')
                }
            })
        } else {
            //  如果校验不通过，记得要返回false，让表单组件显示提示信息
            return false
        }
    })
}

</script>

<style lang="less" scoped>
.login {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #2d3a4b;
    min-height: 100vh;

    .login-box {
        min-width: 400px;

        .el-button {
            width: 100%;
        }

    }
}
</style>